import React, { Component } from 'react';
import { Menu} from 'antd';
import {NavLink} from 'react-router-dom';
// 通过connect将react和redux连接起来
import {connect} from 'react-redux';
// 通过事件触发
import {switchMenu} from './../../redux/action';
import './index.less'
import menuConfig from '../../config/menuConfig'
const SubMenu = Menu.SubMenu;


class NavLeft extends Component {
    state = {
        currentKey: ''
    }
    // 生命周期
    componentWillMount() {
        const menuTreeNode = this.renderMenu(menuConfig);
        // 以#开头或者?或者?之后的任意字符结尾的的都设置为空
        let currentKey = window.location.hash.replace(/#|\?.*$/g, '');
        
        // TODO
        // 刷新页面，面包屑还是显示当前选中的菜单项

        this.setState({
            currentKey,
            menuTreeNode
            
        })
    }
    // params is Object, contain reference item、key、keyPath
    handleMenuClick = (params) => {
        console.log(params.item.props.children.props.children)
        // 通过connect关联之后，可以通过dispatch派发事件，dispatch接受一个action,进而触发更改state命令。
        const {dispatch} = this.props;
        dispatch(switchMenu(params.item.props.children.props.children))
        this.setState({
            currentKey: params.key
        })

    }
    renderMenu = (data) => {
        return data.map((item) => {
            if (item.children) {
                return (<SubMenu title={item.title} key={item.key}>
                            {this.renderMenu(item.children)}
                        </SubMenu>)
            }
            return <Menu.Item  key={item.key}>
                        <NavLink to={item.key}>{item.title}</NavLink>
                    </Menu.Item>
        })
    }
    render() {
        return (
            <div>
                <div className="logo">
                    <img src="/assets/img/logo-ant.svg" alt="" className="logo-img"/>
                    <h1 className="logo-title">ManageSystem</h1>
                </div> 
                <Menu theme="dark"
                      selectedKeys={[this.state.currentKey]}
                      onClick={this.handleMenuClick}>
                    {this.state.menuTreeNode}
                </Menu>
            </div>
        );
    }
}
// 将组件丢进redux里面,被redux管理
export default connect()(NavLeft);